package cn.xiuxius.embedded.runtime.rtx51;

import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;

public class TaskClickListener implements BiConsumer<MouseEvent, Point> {


    private final Pattern VALID_PATTERN = Pattern.compile("^[a-zA-Z0-9_]+$");

    private final Editor editor;
    private final PsiElement element;
    private final String oldTaskId;

    public TaskClickListener(Editor editor, PsiElement element, String oldTaskId) {
        this.editor = editor;
        this.element = element;
        this.oldTaskId = oldTaskId;
    }

    @Override
    public void accept(MouseEvent mouseEvent, Point point) {
        String input = Messages.showInputDialog(
                editor.getProject(),
                "输入新的 Task ID:",
                "修改 Task",
                Messages.getQuestionIcon(),
                oldTaskId,
                new InputValidator() {
                    @Override
                    public boolean checkInput(@NlsSafe String s) {
                        return s != null && VALID_PATTERN.matcher(s).matches();
                    }

                    @Override
                    public boolean canClose(@NlsSafe String s) {
                        if (!checkInput(s)) {
                            Messages.showErrorDialog(
                                    editor.getProject(),
                                    "Task ID 无效：只能包含字母、数字和下划线，且不能包含空格",
                                    "输入错误"
                            );
                            return false;
                        }
                        return true;
                    }
                });
        if (input != null && input.matches("^[a-zA-Z0-9_]+$")) {
            WriteCommandAction.runWriteCommandAction(editor.getProject(), () -> {
                String newAnnotationText = "/** _task_ " + input + " **/";
                editor.getDocument().replaceString(
                        element.getTextRange().getStartOffset(),
                        element.getTextRange().getEndOffset(),
                        newAnnotationText
                );
                PsiDocumentManager.getInstance(Objects.requireNonNull(editor.getProject())).commitDocument(editor.getDocument());
            });
        }
    }
}
